# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http.response import JsonResponse
import json
# Create your views here.
from django.contrib.auth.models import User
from django.contrib.auth import login as _login
from django.contrib.auth.decorators import login_required
from django.contrib.auth import  authenticate
from django.core.exceptions import ObjectDoesNotExist

from django.forms import model_to_dict

from .models import  ReportSubcription


def root(request):
    return render(request,template_name="accounts/index.html",context={})
def register(request):
    if request.method=="GET":
        return render(request,template_name="accounts/register.html",context={})

    elif request.method=="POST":
        user=json.loads(request.body)
        errors={}
        isValid=True
        print user
        if user['password']!=user['password2']:
            errors['password2']=u"两次密码不一致。"
            isValid=False
        if user.get('username',None):
           try:
                User.objects.get(username=user['username'])
                errors["username"]=u"用户名已经存在！"
                isValid=False
           except ObjectDoesNotExist:
               pass
        else:
            errors["username"]=u"请输入用户名！"
            isValid=False

        if isValid==True:
            createdUser=User.objects.create_user(username=user['username'],password=user['password'])
            return JsonResponse(data={"status_code":200,"user":user})
        else:
            return JsonResponse(data={"status_code":422,"errors":errors})

        #print user
        return JsonResponse({})


def login(request):
    if request.method == "POST":
        user=json.loads(request.body)
        username=user.get('username',None)
        password=user.get('password',None)
        errors={}
        if  username and password:
            user_cache = authenticate(username=username, password=password)
            if not user_cache:
                errors["_all_"]=u"用户名或密码错误！"
            elif not user_cache.is_active:
                errors["_all_"]=u"账号未激活！"
            else:
                _login(request,user_cache)
            if errors=={}:
                return JsonResponse(data={"status_code": 200,"user":{"username":user_cache.username}})
        if not username:
            errors["username"]="请输入用户名！"
        if not password:
            errors["password"]="请输入密码！"

        return JsonResponse(data={"status_code":422,"errors":errors})

@login_required
def report_subscription_list(request):
    if request.method=="GET":
        qs=ReportSubcription.objects.filter(user=request.user)
        data={"status_code":200,"items":qs}
        return JsonResponse(data)
